<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
ini_set('max_execution_time', '0');

/*******************
***  处理外部123数据库数据
***  http://192.168.1.100:89/fshop/
*** 2017/05/10
**********/
class Amazondata
{

	 public function __construct()
    {
        $this->CI =& get_instance();
        $this->db1 = $this->CI->load->database('default', TRUE);
        //$this->db2 = $this->CI->load->database('amazondata', TRUE);
		$this->CI->load->model('Function_m','fun');
		
    }
	
	/*******************
	***  保存shop信息
	*** 2017/05/10
	**********/	
	public function saveshop($arraydata)
	{	
		foreach($arraydata as $key=>$rs)
		{
			
			$post[$key] = $rs;
		}
	
		$rsdb = $this->db2->get_one("SELECT * FROM d_shop where id='".$post["id"]."'");
		if($rsdb)
		{
			$newpost="";
			$newpost['updateoper'] = $post['updateoper'];
			$newpost['uploadID'] = $post['uploadID'];
			$newpost['otherUpload'] = $post['otherUpload'];
			$newpost['del_flag']  = $post['del_flag'];
			$newpost['amazonkey']  = $post['amazonkey'];
			$newpost['shop_platform_fee']  = $post['shop_platform_fee'];
			$newpost['shop_pay_fee']  = $post['shop_pay_fee'];
			$this->db2->update("d_shop",$newpost," id='".$post["id"]."'");
			
		}else{
			$this->db2->insert("d_shop",$post);
		}
	}

	/*************读取123数据库newamazondb表中的数据到订单列表*********************/
	public function UpdateAmazondata()
	{
		//将日本的订单标上传完成
		
		$this->db1->update("db_order_list",array("is_update_platform"=>2),"shopid in(SELECT id from d_shop where country = 2 and platfrom = 2)  AND `order_source` ='正常订单' AND  is_update_platform = 0 and (`order_status` = 4 or order_status=5 )");
		//$this->db1->update("db_order_list",array("is_update_platform"=>0),"shopid in(SELECT id from d_shop where country = 2 and platfrom = 2) AND is_update_platform = 3");//将所有已更新有引受状态的订单更新成可更新到亚马逊
		$sql="SELECT * FROM `db_order_list` JOIN `d_shop` ON `d_shop`.`id` = `db_order_list`.`shopid` WHERE  (`order_status` = 4 or order_status=5 ) AND (`is_update_platform` =0  or `is_update_platform` =3) AND `d_shop`.`platfrom` = 2 AND `d_shop`.`amazonkey`='' ";
		//$sql="SELECT * FROM `db_order_list` JOIN `d_shop` ON `d_shop`.`id` = `db_order_list`.`shopid` WHERE  1 AND `is_update_platform` =0 AND `d_shop`.`platfrom` = 2 AND `d_shop`.`amazonkey`='' and tradeid='112-8828173-4728239'";
		$query = $this->db1->query($sql);
        $row = $query->result_array();
		
		foreach($row as $key=>$rs)
		{
			$this->db2->trans_begin();	//事务开始
			$rsdb = $this->db2->get_where("fshop.db_synorder"," orderid='".$rs["order_sn"]."'")->result_array();
			if(count($rsdb)==0)
			{
				$rsdbsell = $this->db1->select('goods_number')->get_where("db_order_sell","order_id='".$rs["order_id"]."'")->result_array();
				$rsdbamzonsell = $this->db2->get_one("SELECT A.transactionid FROM fshop.db_amzordertmpsell A LEFT JOIN fshop.db_amzordertmp B ON A.ordertmpid = B.id WHERE B.amzorderid='".$rs["tradeid"]."' ");
			
				$post="";
				$post["orderid"] = $rs["order_sn"];
				$post["tradeid"] = $rs["tradeid"];
				$post["transactionid"] = $rsdbamzonsell["transactionid"];
				$post["ordernum"] = $rsdbsell[0]["goods_number"];

				$post["expressid"] = $rs["shipping_number"];
				$post["expresstypeid"] = $rs["shipping_id"];
				$post["expresstype"] = $rs["shipping_name"];

				//获取亚马逊支持的物流名

				$rsexp = $this->db1->get_one("SELECT * FROM db_order_express WHERE id = '".$rs["shipping_id"]."'");
				if($rsexp)
				{
					$post["nameen"] = $rsexp["amazon_express"];
					$post["filed16"] = $rsexp["amazon_express"];
				}else{
					$post["nameen"] = "Other";
					$post["filed16"] = "Other";
				}
				$post["filed18"] = '';
			
				
				$shopname = $rs["shopname"];
				
				$rsdbshopname = $this->db2->select('sid,name,id')->get_where("fshop.d_shop"," name='".$shopname."'")->result_array();
				
				$post["shoptypeid"] =$rsdbshopname[0]["sid"];
				$post["shoptype"] =$rsdbshopname[0]["name"];
				$post["shopid"] =$rsdbshopname[0]["id"];
				$post["syntime"] =date("Y-m-d H:i:s");
				$post["synflag"] =0;

				
				$this->db2->insert("fshop.db_synorder",$post);
				$this->db1->update("db_order_list",array("is_update_platform"=>1),"order_id=".$rs["order_id"]);

				if ($this->db2->trans_status() === FALSE)
				{
					$this->db2->trans_rollback();
				}
				else
				{
					$this->db2->trans_commit();
				}
			}
		}

		echo "OK";
		die;

		
	}

	/**读取远程的亚马逊订单信息*******/
	public function getlist()
	{
		$row = $this->db2->get_where("db_amzordertmp","flag=1")->result_array();
		if(count($row)>0)
		{
			foreach($row as $key=>$rs)
			{
				
				 //事务处理 整体提交
			$this->db1->trans_begin();
			try{
				$id = $rs["id"];
				$this->db1->insert("db_amzordertmp",$rs);
				//读取sell
				$rowsell = $this->db2->get_where("db_amzordertmpsell","ordertmpid=".$id)->result_array();
				if(count($rowsell)>0)
				{
					foreach($rowsell as $k=>$res)
					{
						if(strstr($res["productid"],"@"))
						{
							$productid = explode("@",$res["productid"]);
							$res["productid"] = $productid[0];

						}
						$this->db1->insert("db_amzordertmpsell",$res);
					}
				}
				$this->db2->update("db_amzordertmp",array("flag"=>2),"id=".$id);	//处理远程数据库标识
				$this->db1->trans_commit();
			}catch (Exception $e){
				$this->db1->trans_rollback();
				$msg =  $e->getMessage();
				print_r($msg);exit;
			}
		  }
		}
		//print_r($row);
	}

	/*************读取123数据库fshop表中的数据到订单列表*********************/
	/********synflag = 1 and ordersource = MFN *************/
	public function getinsertorderlist()
	{
		//$times = date("Y-m-d")." 00:00:00";
		//$time2 = date("Y-m-d")." 23:59:59";
		
		$factorycode = $this->factorycode();
		
		$this->db2->limit(1);
		$row = $this->db2->get_where("fshop.db_sysorder","flag=0 AND ordersource = 'MFN' AND synflag >1 ")->result_array();
		if(count($row)==0)
		{
			return false;
		}
		$rs = $row[0];
		
			$rorder = $this->db1->get_where("db_order_list","tradeid='".$rs["tradeid"]."'")->result_array();
			if($rorder[0]["order_id"])
			{
				$this->db2->update("fshop.db_sysorder",array("flag"=>1),"orderid='".$rs["orderid"]."' AND tradeid='".$rs["tradeid"]."' ");
				return $this->getinsertorderlist();
			}
			if($rs["shopname"]=="yuanyuan"){
				$rs["shopname"] = "YUAN YUAN";
			}
			if($rs["shopname"]=="JP11"){
				$rs["shopname"] = "JP-coshans";
			}

			
				
			$rshop = $this->db1->get_where("d_shop","name='".$rs["shopname"]."'")->result_array();
			$postdata="";
			$postdata["order_sn"] = $this->getNo('amazon',$rs["tradeid"],$rshop[0]["id"]);
			$postdata["dates"] = date("Y-m-d");
			$postdata["order_status"] = $rs["status"];
			$postdata["order_source"] ='正常订单';
			$rsdb = $this->db2->get_where("fshop.db_amzordertmp","amzorderid='".$rs["oringorderid"]."'")->result_array();
			$postdata["customerid"] =addslashes(trim($rsdb[0]["custid"]));
			$postdata["consignee"] =addslashes(trim($rsdb[0]["custname"]));
			$postdata["country"] = $rsdb[0]["custcountry"];
			
			$rscountry = $this->db1->get_where("d_country","countrynamecn='".trim($rsdb[0]["custcountry"])."'")->result_array();
			if($rscountry[0]["id"]){
				$postdata["country_cn"] = $rscountry[0]["countrynameen"];
			}

			$postdata["province"] = $rsdb[0]["custprovince"];
			$postdata["city"] = $rsdb[0]["custcity"];
			$postdata["address"] = addslashes(trim($rsdb[0]["custaddress1"]));
			$postdata["address2"] = addslashes(trim($rsdb[0]["custaddress2"]));
			$postdata["zipcode"] = $rsdb[0]["custzipcode"]?$rsdb[0]["custzipcode"]:0;
			$postdata["tel"] = $rsdb[0]["custtel1"]?$rsdb[0]["custtel1"]:0;
			$postdata["mobile"] = $rsdb[0]["custtel2"];
			$postdata["email"] = $rsdb[0]["custemail"];
			
			
			$postdata['platformID']  = $rshop[0]['platfrom']?$rshop[0]['platfrom']:2;//平台
			$exchange=$this->db1->get_where("d_moneyrate","name='".$rs["moneytype"]."'")->result_array();
			$postdata['moneyrate']  = $exchange[0]["rate"];//汇率

			$postdata["shopname"] = $rshop[0]["name"]?$rshop[0]["name"]:"未知";
			$postdata["shopid"] = $rshop[0]["id"]?$rshop[0]["id"]:0;
			$postdata["shopoper"] = $rshop[0]["updateoper"];
			
			if($rsdb[0]["countrycode"]=="")
			{
				$rscountry = $this->db1->get_where("d_country","countrynamecn='".trim($rsdb[0]["custcountry"])."'")->result_array();
				$country_code = $rscountry[0]['countryid'];
			}else{
				$country_code =  $rsdb[0]["countrycode"];
			}
			$postdata["country_code"] = $country_code;
			$postdata["moneytype"] = $rs["moneytype"];
			$postdata["tradeid"] = $rs["tradeid"];
			$postdata["goods_originask"] = $rsdb[0]['origintotle'] - $rs['originexpressask'];	//原金额
			
			if(!$exchange[0]["rate"])
			{
				$exchange[0]["rate"]= $rs['moneyrate'];
			}

			$goods_amount  =  ($rsdb[0]['origintotle'] - $rs['originexpressask']) * $exchange[0]["rate"];//转换成RMB
			$shipping_fee  =  $rs['originexpressask'] * $exchange[0]["rate"];
			
			$postdata["goods_amount"] = $goods_amount;
			$postdata["shipping_fee"] = $shipping_fee?$shipping_fee:0;
			$postdata["shipping_originask"] = $rs["originexpressask"]?$rs["originexpressask"]:0;//原运费
			$postdata["add_time"] = time();
			$postdata["ordertime"] = $rs["ordertime"];
			$postdata["saleschannel"] = $rs["saleschannel"];
			$postdata["isform"] = 1;
			if($rshop[0]["shop_platform_fee"]>0)
			{
				$shop_platform_fee  =$rshop[0]["shop_platform_fee"];
			}else{
				$shop_platform_fee = 0.15;
			}
			if($rshop[0]["shop_pay_fee"]>0)
			{
				$shop_pay_fee  =$rshop[0]["shop_pay_fee"];
			}else{
				$shop_pay_fee = 0.015;
			}


			$postdata["pay_fee"] = ($goods_amount+ $shipping_fee)*$shop_pay_fee;
			$postdata["platform_fee"] =($goods_amount+ $shipping_fee)*$shop_platform_fee;
			
			
			$this->db1->trans_begin();	//事务开始
			
				$this->db1->insert("db_order_list",$postdata);
				$orderID = $this->db1->insert_id();
				$goods_sku = "";				
				$sell = $this->db2->get_where("fshop.db_syssell","tradeid='".$rs["tradeid"]."'")->result_array();
				$weight = 0;
				foreach($sell as $key=>$res)
				{
					
					/*****************替换SKU方式********
						**  1、是否存在123.fshop数据库d_aotocreatesku表中
						**  2、是否存在在商品的db_goods 中的cognatelist字段
						**  3、是否db_salesku中
					*********************************/
					$productid = "";
					$oldgoodsku = $res["originsku"];
					if(strpos($oldgoodsku,"@") === false){  
						$oldgoodsku = $res["originsku"];
					}else{
						$oldgoodsku = explode("@",$res["originsku"]);
						$oldgoodsku = $oldgoodsku[0];
					}
					$newgoods = $this->db2->get_where("fshop.d_aotocreatesku","autosku='".$oldgoodsku."' AND shopid='".$rs["shopid"]."' ")->result_array();
					if(count($newgoods)>0)
					{
						$productid = $newgoods[0]["parentsku"];
					}else{
						$newgoods = $this->db1->get_where("db_goods","goods_sku='".$oldgoodsku."' ")->result_array(); 
						if(count($newgoods)>0)
						{
							$productid = $newgoods[0]["goods_sku"];
						}else{
							$newgoods = $this->db1->get_where("db_goods","cognatelist like '%,".$oldgoodsku.",%'")->result_array(); 
							if(count($newgoods)>0)
							{
								$productid = $newgoods[0]["goods_sku"];
							}else{
								$newgoods = $this->db1->get_where("db_salesku","autosku='".$oldgoodsku."'")->result_array();//这里一定要对应goods_id信息,不能使用goods_sku
								if(count($newgoods)>0)
								{
									$goods_id = $newgoods[0]["goods_id"];
									$rowrsdb = $this->db1->get_where("db_goods","goods_id='".$goods_id."'")->result_array();
									if(count($rowrsdb)>0)
									{
										$productid = $rowrsdb[0]["goods_sku"];
									}else{
										$productid = $oldgoodsku;
									}
									
								}
							}
						
						}
					
					}

					if(!$productid)
					{
						$productid = $oldgoodsku;
					}


					$rgoods = $this->db1->get_where("db_goods","goods_sku='".$productid."' ")->result_array();
					if(!$rgoods[0]["goods_id"])
					{
						$rgoods = $this->db1->get_where("db_goods"," cognatelist like '%,".$productid.",%'")->result_array();
					}

					if($rgoods[0]["goods_id"])
					{
						$goods_id = $rgoods[0]["goods_id"];
						$goods_sku =  $rgoods[0]["goods_sku"];
						$sweight = $res["ordernum"] * $rgoods[0]["g_weight"];
						$weight = $weight+$sweight;
						/*****************成本价计算方式********
						**  11、12开头定制的衣服按成本价计算
						**  批量的sku 按关联价计算
						**  外采购的衣服按成本价计算
						*********************************/
						$costprice = 0;
						if(is_numeric($productid) && preg_match('|^\d{8}$|',$productid))	//数字并且8位SKU并且11 12开头
						{
							$goodscode  = substr($productid,0,2);//取开头2位数
							if(in_array($goodscode,$factorycode))	//是否存在在工厂code
							{
								$costprice = $rgoods[0]["g_costprice"];	//定制衣服按成本价计算
							}
						}else{
							//如果当前SKU不是8位，查询父SKU是不是8位并且11，12开头
							if(is_numeric($rgoods[0]["goods_parent_sku"]) && preg_match('|^\d{8}$|',$rgoods[0]["goods_parent_sku"]))	//数字并且8位SKU并且11 12开头
							{
								$goodscodes  = substr($rgoods[0]["goods_parent_sku"],0,2);//取开头2位数
								if(in_array($goodscodes,$factorycode))	//是否存在在工厂code
								{
									if($rgoods[0]["bulkprice"]>0)
									{
										$costprice =  $rgoods[0]["bulkprice"];	//批量按关联价计算
									}else{
										$costprice =$rgoods[0]["g_costprice"];	//定制衣服按成本价计算
									}
								}else{
									$costprice =$rgoods[0]["g_costprice"];	//定制衣服按成本价计算
								}
							}else{
								$costprice = $rgoods[0]["g_costprice"];
							}
							
						}
						
					}else{
						$goods_id = 0 ;
						$costprice = 0;
						$goods_sku =  $oldgoodsku;
					}

					
					$postsell = "";
					$postsell["order_id"] = $orderID;
					$postsell["goods_id"] = $goods_id;
					$postsell["goods_name"] = addslashes($res["productname"]);
					$postsell["goods_sn"] = $goods_sku;
					$postsell["costprice"] = $costprice;
					$postsell["goods_number"] = $res["ordernum"];
					$postsell["goods_price"] = $res["sellprice"];
					$postsell["goods_weight"] = $rgoods[0]["g_weight"]?$rgoods[0]["g_weight"]:0;
					$postsell["goods_amount"] = $res["sellamount"];
					$postsell["originsellprice"] = $res["originsellprice"];
					$postsell["originsku"] = $res["originsku"];
					$this->db1->insert("db_order_sell",$postsell);

					if($goods_id==0)
					{
						$this->db1->update("db_order_list",array("order_status"=>7),"order_id=".$orderID);
					}
				}

				if(count($sell)==0)
				{
					$this->db1->update("db_order_list",array("order_status"=>7),"order_id=".$orderID);
				}
				if($weight)
				{
					$this->db1->update("db_order_list",array("orderweight"=>$weight),"order_id=".$orderID);
				}

				//更新日志
				$imgdata["goods_id"] = $orderID;	//订单ID
				$imgdata["updatetime"] = date("Y-m-d H:i:s");
				$imgdata["createUid"] = 0;
				$imgdata["types"] = 3;
				$imgdata["content"] = 'Amazon接口自动新增订单,交易ID='.$rs["tradeid"];
				$imgdata["createUser"] ='auto';
				$this->db1->query($this->db1->insert_string('db_goods_log', $imgdata));
				
				$this->db2->update("fshop.db_sysorder",array("flag"=>1),"orderid='".$rs["orderid"]."' AND tradeid='".$rs["tradeid"]."' ");
				

				if ($this->db1->trans_status() === FALSE)
				{
					$this->db1->trans_rollback();
				}
				else
				{
					$this->db1->trans_commit();
				}


		
			
		return $this->getinsertorderlist();
		
	}

	public  function getNo($shopName='',$tradeid='',$shopid='') {

		if($shopName)
		{
			if($shopName =='wish')
			{
				 $randCode = $this->randCode(5,1);
				 $ors=$randCode.substr(time(),-5).substr(microtime(),2,5);     //生成16位数字基本号
			}
			if($shopName =='amazon')
			{
				if($tradeid)
				{
					$no = str_replace("-","",$tradeid);
					$ors = $shopid.$no;
				}else{
					 $randCode = $this->randCode(5,1);
					 $ors=$randCode.substr(time(),-5).substr(microtime(),2,5);     //生成16位数字基本号
				}
			}
			if($shopName =='ebay')
			{
				if($tradeid)
				{
					$no = str_replace("-","",$tradeid);
					$ors = $no;
					}else{
					 $randCode = $this->randCode(5,1);
					 $ors=$randCode.substr(time(),-5).substr(microtime(),2,5);     //生成16位数字基本号
				}
			}
			if($shopName =='Aliexpress')
			{
				if($tradeid)
				{
					$no = str_replace("-","",$tradeid);
					$ors = $no;
					}else{
					 $randCode = $this->randCode(5,1);
					 $ors=$randCode.substr(time(),-5).substr(microtime(),2,5);     //生成16位数字基本号
				}
			}
            if($shopName =='bonanza'){
                if($tradeid){
                    $no = str_replace("-","",$tradeid);
                    $ors =$shopid.$no;
                }else{
                    $randCode = $this->randCode(5,1);
                    $ors=$randCode.substr(time(),-5).substr(microtime(),2,5);     //生成16位数字基本号
                }
            }
			if($shopName =='magento')
			{
					if($tradeid)
					{
						$no = str_replace("-","",$tradeid);
						$ors =$shopid.$no;
					}else{
					 $randCode = $this->randCode(5,1);
					 $ors=$randCode.substr(time(),-5).substr(microtime(),2,5);     //生成16位数字基本号
				}
			}
		
		}else{
			$randCode = $this->randCode(5,1);
			$ors=$randCode.substr(time(),-5).substr(microtime(),2,5);     //生成16位数字基本号
			/*
			$zigui = "FM";
			$sql = "select max(right( order_sn, 12 ) *1) as hot from db_order_list where dates='" . date("Y-m-d") . "' group by dates ";
			$query = $this->db1->query($sql);
			$hot = $query->result_array();
			if ($hot[0]['hot']) {
				$no = substr($hot[0]['hot'], 8, strlen($hot[0]['hot']));
				$no = $no + 10001;
				$no = date("Ymd") . substr($no, 1, strlen($no));

				$ors =$zigui . $no;
			}
			else
				$ors =$zigui . date("Ymd") . "0001";*/
		}
		$order  = $this->db1->get_where("db_order_list","order_sn ='".$ors."'")->result_array();
		if(count($order)>0)	//如果存在，则自动生成一个无序订单号
		{
			return $this->getNo();
		}else{
			return $ors;
		}

    }
	
	/**
	  +----------------------------------------------------------
	 * 生成随机字符串
	  +----------------------------------------------------------
	 * @param int       $length  要生成的随机字符串长度
	 * @param string    $type    随机码类型：0，数字+大小写字母；1，数字；2，小写字母；3，大写字母；4，特殊字符；-1，数字+大小写字母+特殊字符
	  +----------------------------------------------------------
	 * @return string
	  +----------------------------------------------------------
	 */
	function randCode($length, $type = 0) {
		if($length ==999)
		{
			$length=mt_rand(3,10);
		}
		$arr = array(1 => "123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
		if ($type == 0) {
			array_pop($arr);
			$string = implode("", $arr);
		} elseif ($type == "-1") {
			$string = implode("", $arr);
		} else {
			$string = $arr[$type];
		}
		$count = strlen($string) - 1;
		$code = '';
		for ($i = 0; $i < $length; $i++) {
			$code .= $string[rand(0, $count)];
		}
		return $code;
	}


	public function factorycode()
	{
		$rsdb = $this->db1->get_where("db_factory","code >0")->result_array();
		foreach($rsdb as $key =>$rs)
		{
			$factorycode[] = $rs["code"];	//工厂编号
		}

		return $factorycode;
	}
	
	//将无忧信息保存在远程
	public function savealiexpresswuyou($arraydata,$shopid,$tradeid)
	{
		foreach($arraydata as $key=>$rs)
		{
			$post[$key] = $rs;
		}
		$post["customertel2"] = str_replace("+","",$post["customertel2"]);	//电话中有加号，去掉
		$post["customertel1"] = str_replace("+","",$post["customertel1"]);	//电话中有加号，去掉
		$post['shopid'] = $shopid;
		$post['tradeid'] = $tradeid;
		$post['isupload'] = 0;
		$rsdb = $this->db2->get_one("SELECT * FROM db_aliexpress_wuyou where orderID='".$post["orderID"]."' AND shopid='".$shopid."'");
		if($rsdb)
		{
			$post['isexe'] = 0;
			$this->db2->update("db_aliexpress_wuyou",$post," id='".$rsdb["id"]."'");
		}else{
			$post['isexe'] = 0;
			$this->db2->insert("db_aliexpress_wuyou",$post);
		}
	}

	//从远程读取无忧信息
	public function returnaliexpresswuyou()
	{
		$list = $this->db2->get_where("db_aliexpress_wuyou"," isupload = 0 AND isexe !=0")->result_array();
		if(count($list)>0)
		{
			foreach($list as $key=>$rs)
			{
				if($rs["isexe"] ==1)	//交运成功
				{
					//保存图片到本地
					$postdata="";
					$dir = dirname(__FILE__) . "/../../uploads/wuyexpress/".date("Ymd");
					!is_dir($dir) && @mkdir($dir, 0755, true);
					$Path = $dir. "/".$rs['mailNo']."-".time().".pdf";
					
					if(file_put_contents($Path, base64_decode($rs["printUrl"])))
					{
						
						$pathst = str_replace(dirname(__FILE__) . "/../../", '', $Path);
						$postdata["printUrl"] = $pathst;
						//下载好的pdf转成png
						$rsdbts = $this->CI->fun->pdf2png($Path);
						$postdata["print_img"] = $rsdbts[0];
					}
					$postdata["isexe"] = 1;
					$postdata["exememo"] = "交运成功";
					$postdata["mailNo"] = $rs['mailNo'];
					$postdata["mailinstime"] = $rs['mailinstime'];
					$postdata["originCode"] = 0;
					$postdata["destCode"] = 0;
					$this->db1->update("db_mabangorder",$postdata," orderID='".$rs["orderID"]."' AND customertype='".$rs['customertype']."'");
					$update_order = "";
					$update_order["shipping_number"] = $rs['mailNo'];	//运单号
					$update_order["shipping_time"] = $rs['mailinstime'];				//交运时间
					$update_order["shipping_name"] = "无忧物流";
					$shipping =$this->db1->get_one("select * from db_order_express where name='无忧物流'");
					$update_order["shipping_id"] = $shipping["id"]?$shipping["id"]:22;
					$update_order["shipping_expectfee"] = 0;
					if($rs['isform']==1){
					
					}else{

					$order = $this->CI->fun->getdatabasesdetail('db_order_list', " AND order_sn='".$rs["orderID"]."' AND shopid='".$rs['shopid']."'");
					$this->db1->query($this->db1->update_string('db_order_list', $update_order, "order_sn='".$rs["orderID"]."' AND shopid='".$rs['shopid']."'"));

						//更新日志表db_goods_log
					$imgdata="";
                    $imgdata["goods_id"] = $order['order_id'];	//订单ID db_order_list
                    $imgdata["updatetime"] = date("Y-m-d H:i:s");
                    $imgdata["createUid"] = 0;
                    $imgdata["types"] = 3;
                    $imgdata["content"] = '无忧交运完成,交易ID='.$rs['tradeid'].",运单号=".$rs["mailNo"];
                    $imgdata["createUser"] ='auto';
                    $this->db1->insert('db_goods_log', $imgdata);
						
					}


				}else{
					$post= "";
					$post['isexe'] = $rs['isexe'];
					$post['exememo'] = $rs['exememo'];
					$post['mailinstime'] = $rs['mailinstime'];
					$this->db1->update("db_mabangorder",$post," orderID='".$rs["orderID"]."' AND customertype='".$rs['customertype']."'");
				
				}

				$this->db2->update("db_aliexpress_wuyou",array("isupload"=>1,"printUrl"=>'')," id = '".$rs['id']."'");
			}
		}
		
	}

	public function wishproduct($productid,$shopid,$time,$user,$wpid){
		//判断远程是否存在该商品

		$sql="select count(*) as cou from db_wishproduct where wish_id='{$productid}'";
		$parr=$this->db2->query($sql)->result_array();
        $sum=$parr[0]['cou'];

        if ($sum!=0) {
        $sql2="delete from db_wishproduct where wish_id='{$productid}'";
        $this->db2->query($sql2);
        }
        //导入产品到远程
        //查询产品
        $sql1="select * from db_wishproduct where wish_id='{$productid}';";
        $pro=$this->db1->query($sql1)->result_array();
        $this->db2->insert("db_wishproduct",$pro[0]);


        // 导入远程
          $sql3="insert into db_wish_to_platform values('{$wpid}','{$productid}','{$shopid}','{$time}','{$user}','0','0','');";
          $this->db2->query($sql3);


	}

	public function wishupdata(){
		//从远程更新数据到本地
		$sql1="select * from db_wish_to_platform where is_upload!=0 and is_mabang=0;";
		$res1=$this->db2->query($sql1)->result_array();
		foreach ($res1 as $row1) {
						$wp_id=$row1['wp_id'];
			$is_upload=$row1['is_upload'];
			$log=addslashes($row1['log']);
		//数据更新回本地
		$sql2="UPDATE db_wish_to_platform set is_upload='{$is_upload}',is_mabang='1',log='{$log}' where wp_id='{$wp_id}';";
		$this->db1->query($sql2);
        
        //更新数据到远程
        $sql3="UPDATE db_wish_to_platform set is_mabang='1' where wp_id='{$wp_id}';";
        $this->db2->query($sql3);
		}


	}
	
}